//
//  AccountViewController.m
//  XTXOneToOne
//
//  Created by Canny on 2018/11/1.
//  Copyright © 2018年 WK. All rights reserved.
//

#import "AccountViewController.h"
#import "RealNameAuthModel.h"
#import "RealNameAuthViewController.h"
#import "AccountModel.h"
#import "AddYHKViewController.h"
#import "AccountDeatilViewController.h"
#import "AlipayDetailViewController.h"
#import "AddAlipayViewController.h"
#import "AccountTableViewCell.h"


@interface AccountViewController ()
<
UITableViewDelegate,
UITableViewDataSource,
UIAlertViewDelegate
>
@property (nonatomic,strong)RealNameAuthModel * AuthModel;
@property(nonatomic, strong)UITableView *tableView;

@property (nonatomic,strong)UIView * BGView;


@end

@implementation AccountViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setProperty];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBarHidden=YES;
    
    [self Http_otcpayment_precreate];
    [self Http_otcpayment_getpayment];
    
}

-(void)setProperty{
    
    self.view.backgroundColor=RGB(255, 255, 255);
    
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBarHidden=YES;
    
    self.baseVcTitle = @"收款账户";

}



#pragma mark-什么都没创建
-(void)create_UI1{
    
    /*
     * 背景
     */
    [_BGView removeFromSuperview];
    _BGView = [[UIView alloc]init];
    [self.bgView addSubview:_BGView];
    _BGView.backgroundColor = [UIColor whiteColor];
    [_BGView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bgView.mas_top).offset(0);
        make.right.left.bottom.equalTo(self.bgView);
    }];
    
    UIImageView * timeimgV=[[UIImageView alloc]init];
    [_BGView addSubview:timeimgV];
    timeimgV.image=[UIImage imageNamed:@"卡片"];
    [timeimgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.BGView.mas_top).offset(50);
        make.centerX.equalTo(self.BGView.mas_centerX).offset(0);
        make.height.mas_equalTo(59/2.0);
        make.width.mas_equalTo(73/2.0);
    }];
    
    UILabel * lab = [[UILabel alloc]init];
    [_BGView addSubview:lab];
    [self setLab:lab withColor:RGB(140, 159, 173) andFont:12 andText:@"添加收款方式，买卖更加流畅便捷～" andTextAlignment:NSTextAlignmentCenter];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(timeimgV.mas_bottom).offset(10);
        make.centerX.equalTo(self.BGView.mas_centerX).offset(0);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(300);
    }];
    
    
    UIButton *  btn1 = [[UIButton alloc]init];
    [_BGView addSubview:btn1];
    [btn1 setTitleColor:ThemeColor forState:UIControlStateNormal];
    [btn1 setTitle:@"立即添加" forState:UIControlStateNormal];
//    [btn1 setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    btn1.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    btn1.titleLabel.font = [UIFont boldSystemFontOfSize: 15.0];
    [btn1 addTarget:self action:@selector(actionClick:) forControlEvents:UIControlEventTouchUpInside];
    btn1.tag = 10001;
//    btn1.backgroundColor=RGB(255, 255, 255);
    [btn1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lab.mas_bottom).offset(10);
        make.centerX.equalTo(self.BGView.mas_centerX).offset(0);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(40);
    }];
    
}

-(void)create_UI2{
    /*
     * 背景
     */
    [_BGView removeFromSuperview];
    _BGView = [[UIView alloc]init];
    [self.bgView addSubview:_BGView];
    _BGView.backgroundColor = [UIColor whiteColor];
    [_BGView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bgView.mas_top).offset(0);
        make.right.left.bottom.equalTo(self.bgView);
    }];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;    
    [_BGView addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.BGView).offset(0);
        make.left.equalTo(self.BGView).offset(0);
        make.right.equalTo(self.BGView).offset(0);
        make.bottom.equalTo(self.BGView).offset(0);
    }];
    
    
    UIImageView * imgV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Add_Account"]];
    [self.rightBtn addSubview:imgV];
    [imgV mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.rightBtn.mas_centerY);
        make.right.equalTo(self.rightBtn.mas_right).offset(0);
        make.width.equalTo(@(20));
        make.height.equalTo(@(20));
    }];
 
    [_tableView reloadData];

}

#pragma mark-添加
-(void)rightAction{
   
    [self Http_kyc_findLv1];
    
}


#pragma mark tableView 代理相关
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    AccountModel * Amodel = [AccountModel sharedAccountModel];
    return Amodel.minepayment.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0001;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [AccountTableViewCell computeHeight:@""];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *reuseIdentifier =[NSString stringWithFormat:@"AccountTableViewCell-%ld-%ld",(long)indexPath.section,(long)indexPath.row];
    
    AccountTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[AccountTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    WS(weakSelf);
    
    cell.block = ^(AccountMinePaymentModel * _Nonnull model, BOOL isTurnOn) {
        
        /*
         * 开启
         */
        if (isTurnOn) {
          
            [weakSelf Http_otcpayment_statuspayment:model andStatus:@"1"];
            
            /*
             * 关闭
             */
        }else{
            [weakSelf Http_otcpayment_statuspayment:model andStatus:@"0"];

        }
        
    };
    
    AccountModel * Amodel = [AccountModel sharedAccountModel];

    if (Amodel.minepayment.count>0) {
        cell.dataSource=Amodel.minepayment[indexPath.row];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
    
    
}

/*
修改收款信息状态

1、接口地址

请求方式：post
请求接口：otcpayment/statuspayment/
是否登录：是
2、接口请求参数

参数名    参数类型    含义    备注
payment_id    整型    收款方式id
status    整形    状态    是否开启；@1；开启；@0；关闭
*/
-(void)Http_otcpayment_statuspayment:(AccountMinePaymentModel *)model andStatus:(NSString *)status{
    
    NSString * URL = [NSString stringWithFormat:@"%@otcpayment/statuspayment/",DEFAULTSEVERBASEURL];
    
    WS(weakSelf);
    [HUD showProgress:@"" inView:self.bgView];
    
    NSDictionary * Dic = @{
                           @"payment_id":model.ID,
                           @"status":status,
                           @"access_token":[LoginModel GetValue:DL_token]
                           };
    
    [MOLoadHttpsData PostHttpDataWithUrlStr:URL Dic:Dic SuccessBlock:^(id  _Nonnull responseObject) {
        [HUD dismissInView:weakSelf.bgView];
        
        NSDictionary * dic = responseObject;
        NSString * msg = [NSString stringWithFormat:@"%@",dic[@"msg"]];
        NSString * code = [NSString stringWithFormat:@"%@",dic[@"code"]];
        
        if ([code isEqualToString:@"0"]) {
            
            [HUD showSuccessMessage:msg];
            
            [weakSelf Http_otcpayment_getpayment];
            
        }else{
            [HUD showErrorMessage:msg];
        }
        
        
    } FailureBlock:^(id  _Nonnull error) {
        [HUD dismissInView:weakSelf.bgView];

    }];
    
    
        
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    AccountModel * Amodel = [AccountModel sharedAccountModel];
    AccountMinePaymentModel * model = Amodel.minepayment[indexPath.row];
    if ([model.symbol containsString:@"支付宝"]) {
        AlipayDetailViewController * VC = [[AlipayDetailViewController alloc]init];
        VC.dataSource = model;
        [self.navigationController pushViewController:VC animated:YES];
    }else if ([model.symbol containsString:@"微信"]){
        AlipayDetailViewController * VC = [[AlipayDetailViewController alloc]init];
        VC.dataSource = model;
        [self.navigationController pushViewController:VC animated:YES];
    }else if ([model.symbol containsString:@"银行卡"]){
        AccountDeatilViewController * VC = [[AccountDeatilViewController alloc]init];
        VC.dataSource = model;
        [self.navigationController pushViewController:VC animated:YES];
    }

    
}


-(void)setLab:(UILabel *)lab withColor:(UIColor *)color andFont:(CGFloat)font andText:(NSString *)text andTextAlignment:(NSTextAlignment)textAlignment{
    lab.text=text;
    lab.textColor=color;
    lab.font=[UIFont systemFontOfSize:font];
    lab.textAlignment=textAlignment;
}

-(void)openRZ:(NSString *)text{
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:text delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.delegate=self;
    alert.alertViewStyle = UIAlertViewStyleDefault;
    [alert show];
    
}




-(void)actionClick:(UIButton *)btn{
    
    //立即添加
    if (btn.tag == 10001) {
        
        [self Http_kyc_findLv1];
  
    }
}





#pragma ==========HTTP===========
/*一、获取添加收款方式预备信息
 请求方式：get
 请求接口：otcpayment/precreate
 是否登录：是
 */
#pragma mark-获取添加收款方式预备信息- 能够选择的列表
-(void)Http_otcpayment_precreate{
    
   
    NSString * URL = [NSString stringWithFormat:@"%@otcpayment/precreate",DEFAULTSEVERBASEURL];
    
    WS(weakSelf);
    [HUD showProgress:@"" inView:self.bgView];
    
    [MOLoadHttpsData GetHttpDataWithUrlStr:URL Dic:@{} SuccessBlock:^(id  _Nonnull responseObject) {
        [HUD dismissInView:weakSelf.bgView];
        
        NSDictionary * dic = responseObject;
        
        NSString * code = [NSString stringWithFormat:@"%@",dic[@"code"]];
        NSString * msg = [NSString stringWithFormat:@"%@",dic[@"msg"]];

        if ([code isEqualToString:@"0"]) {

            NSDictionary * dicc = dic[@"data"];
            [weakSelf dealData_otcpayment_precreate:dicc];
        }else{
            
            [weakSelf openRZ:@"实名认证未通过审核，请前往认证！"];
            
        }
            
    } FailureBlock:^(id  _Nonnull error) {
        [HUD dismissInView:weakSelf.bgView];

    }];
    
}

-(void)dealData_otcpayment_precreate:(NSDictionary *)dic{
    NSArray * Arr =  dic[@"payment"];
    AccountModel * Amodel = [AccountModel sharedAccountModel];
    [Amodel.payment removeAllObjects];
    for (NSDictionary *temp in Arr) {
        AccountPaymentModel * model = [[AccountPaymentModel alloc]init];
        model.ID=[NSString stringWithFormat:@"%@",temp[@"id"]];
        model.value=[NSString stringWithFormat:@"%@",temp[@"value"]];
        [Amodel.payment addObject:model];
    }


}

/*

 获取全部收款信息

 请求方式：get
 请求接口：otcpayment/getpayment/
 是否登录：是
 */
#pragma mark- 获取全部收款信息-已经添加过的
-(void)Http_otcpayment_getpayment{
 
    AccountModel * Amodel = [AccountModel sharedAccountModel];
    [Amodel.minepayment removeAllObjects];
    
    NSString * URL = [NSString stringWithFormat:@"%@otcpayment/getpayment/",DEFAULTSEVERBASEURL];
    
    WS(weakSelf);
    [HUD showProgress:@"" inView:self.bgView];
    
    [MOLoadHttpsData GetHttpDataWithUrlStr:URL Dic:@{} SuccessBlock:^(id  _Nonnull responseObject) {
        [HUD dismissInView:weakSelf.bgView];
        
        NSDictionary * dic = responseObject;
        
        NSString * code = [NSString stringWithFormat:@"%@",dic[@"code"]];
        if ([code isEqualToString:@"0"]) {
            
            NSArray * arr = dic[@"data"];
            
            [weakSelf dealData_otcpayment_getpayment:arr];
            
        }
        
    } FailureBlock:^(id  _Nonnull error) {
        
        [HUD dismissInView:weakSelf.bgView];
        
    }];
    
}

-(void)dealData_otcpayment_getpayment:(NSArray *)arr{
    if (![arr isKindOfClass:[NSArray class]]) {
        return;
    }
    
    AccountModel * Amodel = [AccountModel sharedAccountModel];
    [Amodel.minepayment removeAllObjects];
    for (NSDictionary * temp in arr) {
        AccountMinePaymentModel * model = [AccountMinePaymentModel mj_objectWithKeyValues:temp];
        model.status = [NSString stringWithFormat:@"%@",temp[@"status"]];
        [Amodel.minepayment addObject:model];

    }
    
    //没有数据
    if (Amodel.minepayment.count<1) {
       
        [self create_UI1];
        
    //有数据
    }else{
        
        [self create_UI2];
        
    }
    
    
}


-(void)Http_kyc_findLv1{
    NSString * URL = [NSString stringWithFormat:@"%@kyc/findLv1",DEFAULTSEVERBASEURL];
    __weak __typeof(self)wself = self;
    NSDictionary * Dic = @{
                           };
    
    [HUD showProgress:@"" inView:self.view];
    [MOLoadHttpsData GetHttpDataWithUrlStr:URL Dic:Dic SuccessBlock:^(id  _Nonnull responseObject) {
        [HUD dismissInView:self.view];
        NSDictionary * dic = responseObject;
        
        NSString * code = [NSString stringWithFormat:@"%@",dic[@"code"]];
        if ([code isEqualToString:@"0"]) {
            
            NSDictionary * dicc = dic[@"data"];
            wself.AuthModel = [RealNameAuthModel mj_objectWithKeyValues:dicc];
            
            //弹出添加账户
            [wself popselectedAccountList];
            
        }else if([code isEqualToString:@"101012"]){
            //没认证
            
            [wself openRZ:@"您的实名认证尚未完善，请前往认证！"];
            
        }else if([code isEqualToString:@"104013"]){
            //
            [wself openRZ:@"您的实名认证尚未通过，请前往认证！"];
        }
        
        
    } FailureBlock:^(id  _Nonnull error) {
        
        
        [HUD dismissInView:self.view];
        
    }];
    
}


#pragma mark-弹出选择收款方式
-(void)popselectedAccountList{
    
    AccountModel * Amodel = [AccountModel sharedAccountModel];
    
    if (Amodel.payment.count<1) {
        [HUD showErrorMessage:@"暂不能添加！"];
        return;
    }
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"选择收款方式" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    //默认只有标题 没有操作的按钮:添加操作的按钮 UIAlertAction
    
    UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        NSLog(@"取消");
        
        
    }];
    
    WS(weakSelf);
    for (AccountPaymentModel * model in Amodel.payment) {
        //添加确定
        UIAlertAction *sureBtn = [UIAlertAction actionWithTitle:model.value style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull   action) {
            NSLog(@" %@----",model.value);
            [weakSelf GoToAddVC:model];
            
        }];
        //设置`确定`按钮的颜色
        [sureBtn setValue:MC_THEME_COLOR forKey:@"titleTextColor"];
        [alertVc addAction :sureBtn];
    }
    
    //将action添加到控制器
    [alertVc addAction:cancelBtn];
    
    //展示
    [self presentViewController:alertVc animated:YES completion:nil];
    
   
    
}

-(void)GoToAddVC:(AccountPaymentModel *)model{
    
    if ([model.value containsString:@"支付宝"]) {
        AddAlipayViewController * VC = [[AddAlipayViewController alloc]init];
        VC.Type = AddAlipayVCType_Alipay;
        VC.paytype_id=model.ID;
        [self.navigationController pushViewController:VC animated:YES];
    }else if ([model.value containsString:@"微信"]){
        AddAlipayViewController * VC = [[AddAlipayViewController alloc]init];
        VC.paytype_id=model.ID;
        VC.Type = AddAlipayVCType_Weichat;
        [self.navigationController pushViewController:VC animated:YES];
    }else if ([model.value containsString:@"银行卡"]){
        AddYHKViewController * VC = [[AddYHKViewController alloc]init];
        VC.paytype_id=model.ID;
        [self.navigationController pushViewController:VC animated:YES];

    }

}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
  
    if (buttonIndex == 1) { //确认
        
        RealNameAuthViewController * VC = [[RealNameAuthViewController alloc]init];
//        VC.Status = @"UI_1";
        [self.navigationController pushViewController:VC animated:YES];
        
    }else{
        [self.navigationController popViewControllerAnimated:YES];
        
    }

    
}



@end



















